package com.eostoken.eos_wallet.base;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.util.FragmentUtils;
import com.eostoken.eos_wallet.R;
import com.fredy.mvp.BaseMvpActivity;
import com.fredy.mvp.BasePresenter;
import com.fredy.mvp.BaseView;
import com.fredy.mvp.Model;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.util.List;

import butterknife.ButterKnife;

public abstract class BaseActivity<M extends Model, V extends BaseView, P extends BasePresenter>
        extends BaseMvpActivity<M, V, P> implements BaseView {

    /***是否显示状态栏*/
    private boolean isShowState = true;
    /***封装toast对象**/
    private static Toast toast;
    /***获取TAG的activity名称**/
    protected final String TAG = this.getClass().getSimpleName();

    private QMUITipDialog loadingDialog;
    private QMUITipDialog mTipDialog;
    private InputMethodManager manager = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isShowState()) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        setContentView(getContentView());
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        QMUIStatusBarHelper.translucent(this);
        //设置布局
        setContentView(getContentView());

        ButterKnife.bind(this);
        //设置数据
        initData();
        //初始化控件
        initView();

    }

    public abstract int getContentView();

    protected abstract void initData();

    public abstract void initView();


    /**
     * 设置是否显示状态栏
     */
    public abstract boolean isShowState();

    /**
     * 显示长toast
     *
     * @param msg
     */
    public void toastLong(String msg) {
        if (null == toast) {
            toast = new Toast(this);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setText(msg);
            toast.show();
        } else {
            toast.setText(msg);
            toast.show();
        }
    }

    /**
     * 显示短toast
     *
     * @param msg
     */
    public void toastShort(String msg) {
        if (null == toast) {
            toast = new Toast(this);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setText(msg);
            toast.show();
        } else {
            toast.setText(msg);
            toast.show();
        }
    }

    public View getEmptyView(int mipmap, String tip) {
        View view = LayoutInflater.from(this).inflate(R.layout.view_empty, null, false);
        AppCompatImageView mIv = view.findViewById(R.id.iv_empty);
        mIv.setImageResource(mipmap);
        AppCompatTextView mTvTip = view.findViewById(R.id.tv_tip);
        mTvTip.setText(tip);
        return view;
    }


    /**
     * 显示提示对话框
     *
     * @param msg
     */
    public void showTipDialog(String msg) {
        mTipDialog = new QMUITipDialog.Builder(this)
                .setTipWord(msg)
                .create();
        mTipDialog.show();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dismissTipDialog();
            }
        }, 800);
    }

    public void dismissTipDialog() {
        if (mTipDialog != null) {
            if (mTipDialog.isShowing()) { //check if dialog is showing.

                //get the Context object that was used to great the dialog
                Context context = ((ContextWrapper) mTipDialog.getContext()).getBaseContext();

                //if the Context used here was an activity AND it hasn't been finished or destroyed
                //then dismiss it
                if (context instanceof Activity) {
                    if (!isInvalidContext())
                        mTipDialog.dismiss();
                } else //if the Context used wasnt an Activity, then dismiss it too
                    mTipDialog.dismiss();
            }
        }
        mTipDialog = null;
    }

    public void dismissLoadingDialog() {
        if (loadingDialog != null) {
            if (loadingDialog.isShowing()) { //check if dialog is showing.

                //get the Context object that was used to great the dialog
                Context context = ((ContextWrapper) loadingDialog.getContext()).getBaseContext();

                //if the Context used here was an activity AND it hasn't been finished or destroyed
                //then dismiss it
                if (context instanceof Activity) {
                    if (!isInvalidContext())
                        loadingDialog.dismiss();
                } else {//if the Context used wasnt an Activity, then dismiss it too
                    loadingDialog.dismiss();
                }
            }
        }
        loadingDialog = null;
    }

    @Override
    public void showLoading() {
        if (null == loadingDialog) {
            loadingDialog = new QMUITipDialog.Builder(this)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                    .setTipWord(getString(R.string.str_loading))
                    .create();
        }
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        dismissLoadingDialog();
    }

    @Override
    public void showNetError() {

    }


    @Override
    public void finishRefresh() {

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (getSupportFragmentManager().getBackStackEntryCount() < 1) {
            finish();
        } else {
            FragmentUtils.pop(getSupportFragmentManager());
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    @Override
    protected void onResume() {
        super.onResume();

    }


    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissLoadingDialog();
        dismissTipDialog();

//        List<Fragment> fragmentList = FragmentUtils.getFragments(getSupportFragmentManager());
    }

//    public void showTipDialog(String text, TipDialogConfirmListener listener) {
//        View view = LayoutInflater.from(this).inflate(R.layout.dialog_single_button_layout, null, false);
//        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();
//        Window window = dialog.getWindow();
//        window.setBackgroundDrawableResource(android.R.color.transparent);
//        dialog.setCanceledOnTouchOutside(false);
//
//        TextView content = view.findViewById(R.id.tv_content);
//        TextView confirm = view.findViewById(R.id.tv_confirm);
//
//        content.setText(text);
//        confirm.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dialog.dismiss();
//                listener.onConfirm();
//
//            }
//        });
//        dialog.show();
//        dialog.getWindow().setLayout((ScreenUtils.getScreenWidth() / 4 * 3), LinearLayout.LayoutParams.WRAP_CONTENT);
//    }

    public interface TipDialogConfirmListener {
        void onConfirm();
    }

//    public void showTwoBtnDialog(String text, String leftBtn, String rightBtn, TwoBtnDialogListener listener) {
//        View view = LayoutInflater.from(this).inflate(R.layout.dialog_two_button_layout, null, false);
//        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();
//        Window window = dialog.getWindow();
//        window.setBackgroundDrawableResource(android.R.color.transparent);
//        dialog.setCanceledOnTouchOutside(false);
//
//        TextView content = view.findViewById(R.id.tv_content);
//        TextView confirm = view.findViewById(R.id.tv_confirm);
//        TextView cancel = view.findViewById(R.id.tv_cancel);
//
//        content.setText(text);
//
//        if (!ObjectUtils.isEmpty(leftBtn)) {
//            cancel.setText(leftBtn);
//        }
//
//        if (!ObjectUtils.isEmpty(rightBtn)) {
//            confirm.setText(rightBtn);
//        }
//        confirm.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dialog.dismiss();
//                listener.onPositive();
//
//            }
//        });
//
//        cancel.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dialog.dismiss();
//                listener.onNegative();
//
//            }
//        });
//        dialog.show();
//        dialog.getWindow().setLayout((ScreenUtils.getScreenWidth() / 4 * 3), LinearLayout.LayoutParams.WRAP_CONTENT);
//    }

    public interface TwoBtnDialogListener {
        void onPositive();

        void onNegative();
    }

    private boolean isInvalidContext() {
        return (isDestroyed() || isFinishing());
    }

    /**
     * 添加 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void addFragment(int containerViewId, Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(containerViewId, fragment);
        fragmentTransaction.commit();
    }

    /**
     * 添加 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void addFragment(int containerViewId, Fragment fragment, String tag) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        // 设置tag，不然下面 findFragmentByTag(tag)找不到
        fragmentTransaction.add(containerViewId, fragment, tag);
        fragmentTransaction.addToBackStack(tag);
        fragmentTransaction.commit();
    }

    /**
     * 替换 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void replaceFragment(int containerViewId, Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(containerViewId, fragment);
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    /**
     * 替换 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void replaceFragment(int containerViewId, Fragment fragment, String tag) {
        if (getSupportFragmentManager().findFragmentByTag(tag) == null) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            // 设置tag
            fragmentTransaction.replace(containerViewId, fragment, tag);
            fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            // 这里要设置tag，上面也要设置tag
            fragmentTransaction.addToBackStack(tag);
            fragmentTransaction.commit();
        } else {
            // 存在则弹出在它上面的所有fragment，并显示对应fragment
            getSupportFragmentManager().popBackStack(tag, 0);
        }
    }
}
